package main;

import java.io.IOException;
import java.util.regex.*;

import main.CheckType.VariableType;

public class CorrectnessAndHandle {
	
	public static Variable handleVariable(String line, boolean isParam) throws compilationException {
		Pattern pattern = Pattern.compile("("+CheckType.FINAL+" )?(.*) (([a-zA-Z]\\w*)|(_\\w+))((=)(.*))?;");
		Matcher matcher = pattern.matcher(line);
		if (matcher.find()) {
			boolean isFinal=false;
			if (matcher.group(1)!=null)
				isFinal=true;
			if (!CheckType.isVariableType(matcher.group(2)))
				throw new compilationException("Error 3: UnKnown variable type");
			if (!CheckType.isValidVariableName(matcher.group(3)))
				throw new compilationException("Error 4: Unsupported variable name");
			if (isParam && matcher.group(8)!=null)
				throw new compilationException("Error 21: parameter can't get value");
			
			Variable tempVariable;
			if (isParam)
				tempVariable = new Variable(isFinal, matcher.group(2), matcher.group(3));
			else
				tempVariable = new Variable(isFinal, matcher.group(2), matcher.group(3), matcher.group(8));
			
			return tempVariable;
		}
		throw new compilationException("Error 7: UnKnown variable declarition");
	}
	
	public static Method handleMethod(String line) throws compilationException, IOException {
		Pattern pattern = Pattern.compile("(.*) ([a-zA-Z]\\w*)\\((.*)\\)\\{");
		Matcher matcher = pattern.matcher(line);
		if (matcher.find()) {
			if (!CheckType.isMethodType(matcher.group(1)))
				throw new compilationException("Error 22: UnKnown method type");
			Method tempMethod= new Method (matcher.group(1),matcher.group(2));
			String[] parameters =  matcher.group(3).split(",");
			for (String p: parameters) {
				if (!p.equals(""))
					tempMethod.addParameter(handleVariable(p, true));
			}
			
			boolean isCloesd=false;
			Sjavac.nextLine();
			TextProcessor.cleanCode();
			int i=1;
			while (Sjavac.line!=null) {
				if(Sjavac.line.matches(".*\\{"))
					i++;
				if (Sjavac.line.matches("\\}"))
					i--;
				if (i==0) {	
					isCloesd=true;
					break;
				}
				tempMethod.addLine(Sjavac.line);
				Sjavac.nextLine();
				TextProcessor.cleanCode();
			}
			if (!isCloesd)
				throw new compilationException("Error 6: Uncloesd method");
			Sjavac.nextLine();
			
			return tempMethod;
		}
		throw new compilationException("Error 7: UnKnown method declarition");
		
	}
	
	public static boolean isExistMethod (String name) {
		boolean isExist=false;
		for (Method m: Sjavac.methods) {
			if (m.getName().equals(name))
				isExist=true;
		}
		return isExist;
	}
	public static boolean isExistMember (String name) {
		boolean isExist=false;
		for (Variable v: Sjavac.members) {
			if (v.getName().equals(name))
				isExist=true;
		}
		return isExist;
	}
	
}
